from django import forms
from django.db.models import Q
from django.forms.extras.widgets import SelectDateWidget
from django.core.exceptions import *
from django.forms import *
from models import *
from datetime import *
import string

#---------------------------------------------login form-------------------------------------
class LoginForm(Form):
        username = CharField(widget=TextInput(), label='User Name', error_messages={'required':'Please enter a username'})
        password = CharField(widget=PasswordInput(render_value=False), label='Password', error_messages={'required':'Please enter a password'})

        def clean_username(self):
                data = self.cleaned_data['username']

                if string.strip(data) == '':
                        raise ValidationError(u'Please enter a username')

                try:
                        userobj = User.objects.get(username=data, account_status=1)
                except User.DoesNotExist:
                        raise ValidationError(u'This username doesn\'t exist')

                return string.strip(data)

        def clean_password(self):
                password = self.cleaned_data['password']

                if string.strip(password) == '':
                	raise ValidationError(u'Please enter a password')

                try:
                        username = self.cleaned_data['username']
                        userobj = User.objects.get(username=username, password=password)
                except KeyError:
                        """ if error in username """
                        pass
                except User.DoesNotExist:
                        raise ValidationError(u'Login failed!!!')

                return password


#------------------------------register form--------------------
class RegisterForm(ModelForm):
        confirm_password = CharField(widget=PasswordInput(render_value=False), label='Confirm Password', help_text='Please enter your password again', error_messages={'required':'This field is required'})

        class Meta:
                model = User
                fields=('username', 'firstname', 'lastname', 'affiliation', 'email', 'home_page_url', 'password', 'confirm_password')
                widgets = {
                        'password' : PasswordInput(render_value=False)
                }               

        def clean_firstname(self):
                data = self.cleaned_data['firstname']
                return string.strip(data)
        
        def clean_lastname(self):
                data = self.cleaned_data['lastname']
                return string.strip(data)

	def clean_affiliation(self):
                data = self.cleaned_data['affiliation']
                return string.strip(data)
        
	def clean_home_page_url(self):
                data = self.cleaned_data['home_page_url']
                return string.strip(data)

	def clean_email(self):
                data = self.cleaned_data['email']
                userobj = User.objects.filter(email=data)

                if len(userobj) > 0:
                        raise ValidationError(u'This email is already taken by another user. Please provide another email ID.')

                return string.strip(data)

        def clean_username(self):
                data = self.cleaned_data['username']
                userobj = User.objects.filter(username=data)

                for ch in data:
                        if ch not in string.letters + string.digits + "_.":
                                raise ValidationError(u'A username can only contain alphabets, digits, underscores ( _ ) and dots ( . )')

                if len(userobj) > 0:
                        raise ValidationError(u'This username is already taken by another user. Please choose another username')

                return string.strip(data)

        def clean_password(self):
                data = self.cleaned_data['password']
                if len(data) < 6:
                        raise ValidationError(u'Password must be of mimimum 6 characters')

                for ch in data:
                        if ch not in string.ascii_letters + string.digits + string.punctuation:
                                raise ValidationError(u'Password must contain only alphabets, digits and standard punctuation marks.')

                return data

	def clean_confirm_password(self):
                data = self.cleaned_data['confirm_password']
                try:
                        pwd = self.cleaned_data['password']
                        if data != pwd:
                                raise ValidationError(u'Password doesn\'t match')
                except KeyError:
                        """if password is of length<8, cleaned_data['password'] doesnt exist"""
                        pass

                return data



#--------------------------------------------edit personal info form-------------------------------------------------
class AccountForm(ModelForm):	
	new_password = CharField(widget=PasswordInput(render_value=False), label='New Password', help_text='Please enter your new password', required=False)
	confirm_password = CharField(widget=PasswordInput(render_value=False), label='Confirm Password', help_text='Please enter your password again', required=False)
	class Meta:
		model = User		
		fields=('firstname', 'lastname', 'affiliation', 'email', 'home_page_url', 'new_password', 'confirm_password')

	def clean_firstname(self):
		data = self.cleaned_data['firstname']	
		return string.strip(data)
	
	def clean_lastname(self):
		data = self.cleaned_data['lastname']	
		return string.strip(data)
	
	def clean_email(self):
		data = self.cleaned_data['email']
		userobj = User.objects.filter(email=data).filter(~Q(id=self.instance.id))

                if len(userobj) > 0:
                	raise ValidationError(u'This email is already taken by another user.')
			
		return string.strip(data)
		
	def clean_home_page_url(self):
                data = self.cleaned_data['home_page_url']
                return string.strip(data)

	def clean_new_password(self):
                data = self.cleaned_data['new_password']
                if len(data) < 6 and data != '':
                        raise ValidationError(u'Password must be of mimimum 6 characters')

                for ch in data:
                        if ch not in string.ascii_letters + string.digits + string.punctuation:
                                raise ValidationError(u'Password must contain only alphabets, digits and standard punctuation marks.')

                return data

	def clean_confirm_password(self):
                data = self.cleaned_data['confirm_password']
                try:
                        pwd = self.cleaned_data['new_password']
                        if data != pwd and pwd != '':
                                raise ValidationError(u'Password doesn\'t match')
                except KeyError:
                        """if password is of length<8, cleaned_data['password'] doesnt exist"""
                        pass

                return data

	def save(self):
                user = self.instance	
		if self.cleaned_data['new_password'] != '':
			user.password = self.cleaned_data['new_password']
		user.save()




